package com.kevin.utility.common;

import java.util.Date;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.kevin.utility.entity.EmailEntity;
import com.kevin.utility.entity.LiveAuthenticator;

/**
 * @author juntao.lai
 * @since 2015年1月15日
 *
 */
public class EmailUtil {
    
    private static Logger logger = Logger.getLogger(EmailUtil.class);
    
    /**
     * @param email
     * @throws MessagingException 
     */
    public static void sendMail(String emailHost, String emailAccount, String emailPassword, EmailEntity email) throws MessagingException{
        Properties properties = new Properties();
        properties.put("mail.smtp.host", emailHost);
        properties.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(properties, new LiveAuthenticator(emailAccount, emailPassword));
        logger.info("创建连接session成功。");
        MimeMessage mimeMessage = new MimeMessage(session);
        if (email.getMailTOAddress() != null) {
            mimeMessage.addRecipients(javax.mail.Message.RecipientType.TO, email.getMailTOAddress());
        }
        if (email.getMailCCAddress() != null) {
            mimeMessage.addRecipients(javax.mail.Message.RecipientType.CC, email.getMailCCAddress());
        }
        if (email.getMailBCCAddress() != null) {
            mimeMessage.addRecipients(javax.mail.Message.RecipientType.BCC, email.getMailBCCAddress());
        }
        mimeMessage.setSubject(email.getMailSubject());
        mimeMessage.setContent(email.getMailBody());
        mimeMessage.setFrom(email.getMailFromAddress());
        mimeMessage.setSentDate(new Date());
        //Transport transport = session.getTransport("smtp");
        //transport.connect(emailHost, emailAccount, emailPassword);
        Transport.send(mimeMessage);
    }
}